// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: jhkim, junglekim

#include <sys/types.h>
#include <random>

namespace coin2::strategy::cmm_strat {

inline double GenRandomPeriod(int64_t avg_period_min, double range) {
  std::uniform_real_distribution<double> distribution(
      avg_period_min * (1 - range),
      avg_period_min * (1 + range));
  std::random_device rd;
  std::default_random_engine generator(rd());
  double period = distribution(generator);

  return period;
}

struct Timer {
  int64_t elapsed_time = 0;
  int64_t start_time = 0;
  int64_t last_post_time = 0;
  double cur_period_min = 0;
  double avg_period_min = 0;
  double range = 0;
  bool running = true;

  void SetTimer(double avg_period_min_, double range_) {
    avg_period_min = avg_period_min_;
    range = range_;
  }

  void Update(int64_t timestamp_) {
    elapsed_time = timestamp_ - start_time;
    if (elapsed_time > cur_period_min * 6e10) {
      running = false;
    }
  }

  void StartTimer(int64_t timestamp_) {
    start_time = timestamp_;
    cur_period_min = GenRandomPeriod(avg_period_min, range);
    running = true;
    last_post_time = 0;
  }

  void UpdatePostTime(int64_t timestamp_) {
    last_post_time = timestamp_;
  }
};
}  // namespace coin2::strategy::cmm_strat
